<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="账号">
          <el-input v-model="searchForm.uaccount" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.uname" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.uemail" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="user-list-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </template>

      <el-table :data="userList" style="width: 100%" v-loading="loading">
        <el-table-column prop="uid" label="用户ID" width="80" />
        <el-table-column prop="uaccount" label="账号" width="120" />
        <el-table-column prop="uname" label="姓名" width="100" />
        <el-table-column prop="uemail" label="邮箱" width="180" />
        <el-table-column prop="utel" label="手机号" width="120" />
        <el-table-column prop="udelete" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.udelete === 0 ? 'success' : 'danger'">
              {{ scope.row.udelete === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="uregtime" label="注册时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.udelete === 0 ? 'danger' : 'success'" 
              link 
              @click="handleToggleStatus(scope.row)">
              <el-icon><Switch /></el-icon>
              {{ scope.row.udelete === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      @close="handleDialogClose">
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="80px">
        <el-form-item label="账号" prop="uaccount">
          <el-input v-model="userForm.uaccount" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="uname">
          <el-input v-model="userForm.uname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="uemail">
          <el-input v-model="userForm.uemail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="utel">
          <el-input v-model="userForm.utel" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="upwd" v-if="dialogType === 'add'">
          <el-input v-model="userForm.upwd" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Plus, Edit, Delete, Switch,
  House, Box, Document, UserFilled, TrendCharts, Setting 
} from '@element-plus/icons-vue'
import { getAllUserList,save,add } from '@/api/user'

// 搜索表单
const searchForm = reactive({
  uaccount: '',
  uname: '',
  uemail: ''
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref()

// 用户表单
const userForm = reactive({
  uid: '',
  uaccount: '',
  uname: '',
  uemail: '',
  utel: '',
  upwd: ''
})

// 表单验证规则
const userRules = {
  uaccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  uname: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  uemail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  utel: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  upwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取用户列表
const getUserList = () => {
  loading.value = true
  
  // 调用API获取用户数据
  getAllUserList().then(res => {
    if (res.data) {
      console.log('获取用户列表成功:', res.data)
      
      // 前端筛选逻辑
      let filteredData = res.data
      
      // 根据搜索条件过滤
      if (searchForm.uaccount) {
        filteredData = filteredData.filter(user => 
          user.uaccount.toLowerCase().includes(searchForm.uaccount.toLowerCase())
        )
      }
      
      if (searchForm.uname) {
        filteredData = filteredData.filter(user => 
          user.uname.toLowerCase().includes(searchForm.uname.toLowerCase())
        )
      }
      
      if (searchForm.uemail) {
        filteredData = filteredData.filter(user => 
          user.uemail.toLowerCase().includes(searchForm.uemail.toLowerCase())
        )
      }
      
      // 分页处理
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      const paginatedData = filteredData.slice(start, end)
      
      // 设置数据
      userList.value = paginatedData
      total.value = filteredData.length
    }
    loading.value = false
  }).catch(error => {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    loading.value = false
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.uaccount = ''
  searchForm.uname = ''
  searchForm.uemail = ''
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单
  Object.assign(userForm, {
    uid: '',
    uaccount: '',
    uname: '',
    uemail: '',
    utel: '',
    upwd: ''
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(userForm, {
    uid: row.uid,
    uaccount: row.uaccount,
    uname: row.uname,
    uemail: row.uemail,
    utel: row.utel
  })
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = (row) => {
  const action = row.udelete === 0 ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}用户 "${row.uname}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 构建更新后的用户数据
    const updatedUser = {
      ...row,
      udelete: row.udelete === 0 ? 1 : 0
    }
    
    // 调用API更新用户状态
    save(updatedUser).then(() => {
      ElMessage.success(`${action}成功`)
      // 重新加载用户列表
      getUserList()
    }).catch(error => {
      console.error('更新用户状态失败:', error)
      ElMessage.error('更新用户状态失败')
    })
  }).catch(() => {})
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.uname}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用API删除用户
    deleteUserById(row.uid).then(() => {
      ElMessage.success('删除成功')
      // 重新加载用户列表
      getUserList()
    }).catch(error => {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    })
  }).catch(() => {})
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 提交表单
const handleSubmit = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 构建用户数据
      const userData = {
        ...userForm,
        udelete: dialogType.value === 'add' ? 0 : userForm.udelete
      }
      if(dialogType.value === 'add'){
        // 调用API新增用户
        add(userData).then(() => {
          ElMessage.success('新增用户成功')
          dialogVisible.value = false
          // 重新加载用户列表
          getUserList()
        }).catch(error => {
          console.error('新增用户失败:', error)
          ElMessage.error('新增用户失败')
        })
      }else{
        // 调用API保存用户
      save(userData).then(() => {
        ElMessage.success(dialogType.value === 'add' ? '新增用户成功' : '编辑用户成功')
        dialogVisible.value = false
        // 重新加载用户列表
        getUserList()
      }).catch(error => {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败')
      })
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  userFormRef.value?.resetFields()
  Object.assign(userForm, {
    uid: '',
    uaccount: '',
    uname: '',
    uemail: '',
    utel: '',
    upwd: ''
  })
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.user-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>